#pragma strict

var stand_animation:Transform;
var walk_animation:Transform;
var active_animation:Transform;

private var curr_animation:Transform;
private var curr_animation_name:String;

function ChangeAnimation(name:String) {
	if (name != curr_animation_name) {
		//Debug.Log("Mudando animacao de " + curr_animation_name + " para " + name);
		if (curr_animation != null) Destroy(curr_animation.gameObject);		
		if (name == "Stand") curr_animation = Instantiate(stand_animation, transform.position, Quaternion.identity);		
		else if (name == "Walk") curr_animation = Instantiate(walk_animation,transform.position, Quaternion.identity);
		else if (name == "Active") curr_animation = Instantiate(active_animation,transform.position, Quaternion.identity);
		
		curr_animation.parent = transform;
		curr_animation_name = name;
	}
}

function Start () {    
	curr_animation_name = "Stand";
	curr_animation = Instantiate(stand_animation, transform.position, Quaternion.identity);	
	curr_animation.parent = transform;
}

function Update () {	
	// Checa se precisa mudar a animacao
	
	if (SceneManager.Instance().IsGameOver()) {
		if (curr_animation != null) Destroy(curr_animation.gameObject);
	}
	
	if (SceneManager.Instance().IsPlayerAnimationsEnabled()) {
	
		var player_horizontal_speed:float = rigidbody.velocity.x;
		var player_vertical_speed:float = rigidbody.velocity.y;
		
		var anim_script:SimpleSpriteAnim;
		if (curr_animation == null) {
			curr_animation_name = "Stand";
	curr_animation = Instantiate(stand_animation, transform.position, Quaternion.identity);	
	curr_animation.parent = transform;;
		}
		anim_script = curr_animation.gameObject.GetComponent("SimpleSpriteAnim");		
	
		var animation_finished:boolean = anim_script.AnimationFinished();
		
		if (SceneManager.Instance().IsActive()) {
			ChangeAnimation("Active");
		}
		
		else if (Mathf.Abs(player_horizontal_speed) > 0) {
			ChangeAnimation("Walk");
		}
		
		else if (player_horizontal_speed == 0 && player_vertical_speed == 0) {
			ChangeAnimation("Stand");
		}	
		
		if (transform.localScale.x > 0 && player_horizontal_speed > 0) {
			transform.localScale.x *= -1;
		}
		else if (transform.localScale.x < 0 && player_horizontal_speed < 0) {
			transform.localScale.x *= -1;
		}
	}
}
